package com.dk.controller;

import com.dk.bean.Result;
import com.dk.config.IdWorker;
import com.dk.em.ResultEnum;
import com.dk.pojo.CarCustomer;
import com.dk.pojo.CarMessage;
import com.dk.pojo.CarOrder;
import com.dk.service.CarCustomerService;
import com.dk.service.CarMessageService;
import com.dk.service.CarOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("message")
@Api(description = "买车")
public class CarMessageController {

    @Autowired
    private CarMessageService carMessageService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CarCustomerService carCustomerService;

    @Autowired
    private CarOrderService carOrderService;

    @GetMapping
    @ApiOperation(value = "买车车辆信息查询")
    public Result toService(){
        return Result.buildResult(ResultEnum.SUCCESS).setData(carMessageService.toSelect());
    }

    @PostMapping
    @ApiOperation(value = "买车验证(实名,登录)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "用户登陆后放到redis中的登录态", required = true, paramType = "query"),
            @ApiImplicitParam(name = "messageId", value = "商品id", required = true, paramType = "query"),
    })
    public Result toVerification(@RequestParam("uuid")String uuid, @RequestParam("messageId")Long messageId){
        if (!redisTemplate.hasKey(uuid)){
            String str = (String) redisTemplate.opsForValue().get(uuid);//用户名
            CarCustomer carCustomer = carCustomerService.toSelectByName(str);
            CarMessage message = carMessageService.toSelectById(messageId);
            IdWorker idWorker = new IdWorker();
            long ParentOrder = idWorker.nextId();//母订单
            String s1 = String.valueOf(ParentOrder);
            CarOrder order = new CarOrder();
            order.setStatus("0");//订单状态
            order.setCreateTime(new Date());//创建时间
            order.setUserId(carCustomer.getCustomerId());//用户id
            order.setBuyerNick(carCustomer.getUserName());//用户名
            order.setReceiverAreaName(carCustomer.getAddress());//用户地址
            order.setReceiverMobile(carCustomer.getMobilePhone());//用户手机
            order.setParentOrder(s1);//订单号
            order.setMessageId(message.getPrice().longValue());//金额
            order.setBond(5000L);
            return Result.buildResult(ResultEnum.SUCCESS).setData(carOrderService.toInsert(order) + "订单增加成功");
        }
        return Result.buildResult(ResultEnum.SUCCESS).setData("订单增加失败");
    }


}
